package com.leil.bio;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class BIOServer {

    public static void main(String[] args) {
        ServerSocket server = null;
        try {
            // 创建服务监听7777端口
            server = new ServerSocket(7777);
            System.out.println("server start success on 7777......");

            // 等待客户端连接
            while (true) {
                Socket socket = server.accept();
                // 连接到一个新的客户端，创建一个线程处理当前连接
                new Thread(new SocketHandler(socket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                server.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }




}

class SocketHandler implements Runnable {

    private Socket socket;

    public SocketHandler(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();

            byte[] bytes = new byte[1024];
            while (true) {
                int read = inputStream.read(bytes);
                if (read == -1) {
                    break;
                }
                // 在控制台输出发送来的消息
                String req = new String(bytes, 0, read);
                System.out.println("接收到来自客户端的消息：" + req);
                // 将客户端发来的请求写发回给客户端
                String resp = "服务端回复消息";
                outputStream.write(resp.getBytes());
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

